//
//  YKLSUser.m
//  YKLSLiveShow
//
//  Created by zyj on 16/6/7.
//  Copyright © 2016年 leon. All rights reserved.
//

#import "YKLGUser.h"

@interface YKLGUser()

@end

@implementation YKLGUser
@synthesize name;
@synthesize avatarUrl;
@synthesize token;
@synthesize email;

+ (instancetype)shareInstance
{
    static YKLGUser *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (void)setUserName:(NSString *)_name
              avatarUrl:(NSString *)_avatarUrl
              token:(NSString *)_token
              email:(NSString*)_email
{
    avatarUrl = _avatarUrl;
    name = _name;
    token = _token;
    email = _email;
    [[NSUserDefaults standardUserDefaults] setObject:avatarUrl forKey:kUserAvatarUrl];
    [[NSUserDefaults standardUserDefaults] setObject:name forKey:kUserName];
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:kUserToken];
    [[NSUserDefaults standardUserDefaults] setObject:email forKey:kUserEmail];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(NSString *)name
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:kUserName];
}

-(NSString *)token
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:kUserToken];
}

-(NSString *)avatarUrl
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:kUserAvatarUrl];
}

-(NSString *)email
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:kUserEmail];
}
/**
 *  save cookie (when login)
 *
 *  @param cookieArr
 */
- (void)saveCookies:(NSArray<NSHTTPCookie*>*)cookieArr
{
    for(NSHTTPCookie *cookie in cookieArr){
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
}

/**
 *  clear cookie(when logout)
 */
- (void)cleanCookies
{
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookieArray = [NSArray arrayWithArray:[cookieJar cookies]];
    for (id obj in cookieArray) {
        [cookieJar deleteCookie:obj];
    }
}

/**
 *  clear user defaults
 */
- (void)clearUserDefaults
{
    //dont remove all defaults! just remove what you want to remove.
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUserAvatarUrl];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUserName];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUserToken];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kUserEmail];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

/**
 *  logout
 */
- (void)logOut
{
    [self cleanCookies];
    [self clearUserDefaults];
}

/**
 *  has logged in
 */
- (BOOL)isLogin
{
    NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray *cookieArray = [NSArray arrayWithArray:[cookieJar cookies]];
    if([cookieArray count]>0){
        return YES;
    }else{
        return NO;
    }
}
@end
